import axios from 'axios'

// 创建 axios 实例
const request = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080/api',
  timeout: 30000
})

// 请求拦截器 - 添加认证头
request.interceptors.request.use(
  (config) => {
    // 从本地存储获取 token
    const token = localStorage.getItem('authingToken')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    
    console.log('发送请求:', config.method?.toUpperCase(), config.url)
    return config
  },
  (error) => {
    console.error('请求错误:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器 - 处理认证失败
request.interceptors.response.use(
  (response) => {
    return response
  },
  (error) => {
    if (error.response?.status === 401) {
      console.log('认证失败，跳转到登录页')
      // 清除本地存储的用户信息
      localStorage.removeItem('authingToken')
      localStorage.removeItem('userInfo')
      // 跳转到登录页
      window.location.href = '/login'
    }
    
    console.error('响应错误:', error)
    return Promise.reject(error)
  }
)

export default request
